package com.google.code.p.ivans;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cafe.ejb.OrderService;
import cafe.ejb.WaitersOrdersService;
import cafe.ejb.entities.Order;

/**
 * Servlet implementation class AddingOrder
 */
public class AddingOrder extends HttpServlet {
	private static final long serialVersionUID = 1L; 
	
	@EJB
	private OrderService orderSI;
	
	@EJB
	private WaitersOrdersService waitersOrdersSI;
	   
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int table = 1;
		long waiterId = 6;
		try {
			waiterId = Integer.valueOf(request.getParameter("id"));
			table = Integer.valueOf(request.getParameter("table"));
		}
		catch(Exception ignore) {}
		
		// добавляем заказ
		String dishesStr = request.getParameter("dishes");
		
		String[] dishes = dishesStr.split(",");
		List<Integer> dishesKeys = new ArrayList<Integer>();
		
		for(String dish : dishes) {
			try {
				dishesKeys.add(Integer.valueOf(dish));
			}
			catch(Exception ignore) {}
		}
		
		long orderId;
		try {
			Order order = new Order(table, dishesKeys, new GregorianCalendar());			
			orderSI.addOrder(order);
			
			orderId = orderSI.getCurrentId();
			
			// добавляем связь			
			waitersOrdersSI.addLink(waiterId, orderId);
			
			request.setAttribute("result", "Заказ успешно добавлен");
			
		} catch (SQLException e) {			
			e.printStackTrace();
			request.setAttribute("result", "Не удалось добавить заказ. Причина:" + e.getMessage());			
		}
		catch (Exception e) {			
			e.printStackTrace();
			request.setAttribute("result", "Не удалось добавить заказ. Причина:" + e.getMessage());		
		}
		
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("resultOfAddingOrder.jsp");
		requestDispatcher.forward(request, response);
		
	}

}
